from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# from config import OPENAI_API_KEY
from prompt.choice_question_analysis import CHOICE_ERROR_PRONE_POINTS_ANALYSIS_PROMPT
from prompt.reading_comprehension_analysis import (
    READING_ERROR_PRONE_POINTS_ANALYSIS_PROMPT,
)


def choice_question_error_prone_points_analysis(question: str) -> dict:
    """
    这个函数分析用户为什么会选择错误的答案。

    参数:
    question (str): 用户的问题。

    返回:
    dict: 包含分析成功状态、知识点和错误分析以及在分析过程中出现的任何错误的字典。
    """
    try:
        # 分析用户为什么会选错这一道题
        prompt_template = ChatPromptTemplate.from_template(
            CHOICE_ERROR_PRONE_POINTS_ANALYSIS_PROMPT
        )
        llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
        json_parser = JsonOutputParser()
        chain = prompt_template | llm | json_parser
        evaluation_result = chain.invoke({"question_text": question})

        # 组装返回结果
        return {
            "success": True,
            "error_analysis": evaluation_result.get("error_analysis", ""),
        }
    except Exception as e:
        return {"success": False, "analysis": None, "error": str(e)}


def reading_comprehension_error_prone_points_analysis(
    reading_material: str, question_text: str, correct_answer: str
) -> dict:
    try:
        # 分析用户为什么会选错这一道题
        prompt_template = ChatPromptTemplate.from_template(
            READING_ERROR_PRONE_POINTS_ANALYSIS_PROMPT
        )
        llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY)
        json_parser = JsonOutputParser()
        chain = prompt_template | llm | json_parser
        evaluation_result = chain.invoke(
            {
                "reading_material": reading_material,
                "question_text": question_text,
                "correct_answer": correct_answer,
            }
        )

        # 组装返回结果
        return {
            "success": True,
            "error_analysis": evaluation_result.get("error_analysis", ""),
        }
    except Exception as e:
        return {"success": False, "analysis": None, "error": str(e)}
